import React, {Component, Fragment} from 'react';
import {Button, Card, Input, message, Select, Space, Table} from "antd";
import {PlusCircleOutlined, SearchOutlined} from "@ant-design/icons";
import {NavLink} from 'react-router-dom'
import {PAGE_SIZE} from "../../config";
import {reqProductPaginationList, reqProductUpdateStatus, reqProductSearchPaginationList} from '../../api'
import {connect} from "react-redux";
import {saveProductList} from "../../redux/actions/product";

const {Option} = Select;

/**
 * 商品管理路由组件
 */
@connect(
    state => ({}),
    {
        saveProductList
    }
)
class Product extends Component {


    state = {
        dataSource: [], //表格列表数据（分页）
        total: 0, //分页显示总条数
        current: 1, //起始页
        searchKey: '',//搜索关键字
        searchType: 'productName',//搜索类型 默认为productName。productName|productDesc
    }

    componentDidMount() {
        //调用分页列表
        this.getProductPaginationList(1, PAGE_SIZE);
    }

    /**
     * 更新商品状态的逻辑处理
     */
    updateProductStatus = async (id, productStatus) => {
        let dataSource = [...this.state.dataSource];
        productStatus = productStatus === 1 ? 2 : 1;
        const {status, msg} = await reqProductUpdateStatus(id, productStatus);
        if (status === 0) {
            message.success('商品更新状态成功', 2);
            dataSource = dataSource.map(item => {
                if (item._id === id) {
                    item.status = productStatus;
                }
                return item;
            })
            this.setState({dataSource})
        } else {
            message.error(msg, 2);
        }
    }

    /**
     * 点击页码时的逻辑处理
     *
     * @param {*} pagination
     */
    handleTableChange = (pagination) => {
        const {current, pageSize} = pagination;
        this.getProductPaginationList(current, pageSize);
    }

    /**
     * 商品分页列表的逻辑处理
     */
    getProductPaginationList = async (current, pageSize) => {
        let result;
        const {searchKey, searchType} = this.state;
        //判断是否分页查询
        if (this.search) {
            result = await reqProductSearchPaginationList(current, pageSize, searchType, searchKey);
        } else {
            result = await reqProductPaginationList(current, pageSize);
        }

        const {status, msg, data} = result;

        if (status === 0) {
            const {list, total} = data;
            this.setState({
                current,
                dataSource: list,
                total,
            })
            //向redux中保存商品的数据
            this.props.saveProductList(list);
        } else {
            message.error(msg, 2);
        }
    }

    /**
     * 搜索相关逻辑
     */
    handleSearch = async () => {
        //标识是否点击了搜索案例
        this.search = true;
        this.getProductPaginationList(1, PAGE_SIZE);
    }


    render() {

        const columns = [
            {
                title: '商品名称',
                dataIndex: 'name',
                key: 'name',
                width: "15%",
            },
            {
                title: '商品描述',
                dataIndex: 'desc',
                key: 'desc',
            },
            {
                title: '价格',
                dataIndex: 'price',
                key: 'price',
                render: price => '￥' + price,
                width: "10%",
                align: 'center'
            },
            {
                title: '状态',
                render: (item) => {
                    const {_id: id, status} = item;
                    return (
                        <Fragment>
                            <Button type={status === 1 ? 'danger' : 'primary'} onClick={() => {
                                this.updateProductStatus(id, status)
                            }}>{status === 1 ? '下架' : '上架'}</Button>
                            <span>{status === 1 ? '在售' : '已停售'}</span>
                        </Fragment>
                    )
                },
                key: 'status',
                width: "5%",
                align: 'center'
            },
            {
                title: '操作',
                key: 'operator',
                render: (item) => {
                    const {_id: id} = item;
                    return (
                        <Space size="small">
                            <NavLink to={{pathname: '/admin/products/product/view', state: {id}}}>
                                <Button type="link">详情</Button>
                            </NavLink>
                            <NavLink to={{pathname: '/admin/products/product/addUpdate', state: {id}}}>
                                <Button type="link">修改</Button>
                            </NavLink>
                        </Space>
                    )
                },
                width: "5%",
                align: 'center'
            },
        ];

        const {dataSource, total, current} = this.state;

        return (
            <Fragment>
                <Card title={
                    <Fragment>
                        <Select defaultValue={"productName"} onChange={(value) => {
                            this.setState({searchType: value})
                        }}>
                            <Option value="productName">按名称搜索</Option>
                            <Option value="productDesc">按描述搜索</Option>
                        </Select>
                        <Input placeholder="请输入搜索关键字" style={{width: '15%', margin: '0 20px'}} allowClear={true}
                               onChange={e => this.setState({searchKey: e.target.value})}/>
                        <Button type="primary" icon={<SearchOutlined/>} onClick={this.handleSearch}>搜索</Button>
                    </Fragment>
                } extra={<NavLink to={{pathname: "/admin/products/product/addUpdate", state: {}}}>
                    <Button type="primary" icon={<PlusCircleOutlined/>}>添加</Button>
                </NavLink>}>
                    <Table bordered={true} rowKey={"_id"} dataSource={dataSource} columns={columns}
                           pagination={{
                               current,
                               pageSize: PAGE_SIZE,
                               total,
                               showQuickJumper: true,
                           }} onChange={this.handleTableChange}/>
                </Card>

            </Fragment>
        );
    }
}

export default Product
